<template>
  <div class="the-map-component">
    <div id="map"></div>
    <div class="h-check-players">
      <!-- <button @click="test">ReDo</button> -->
      <van-checkbox-group @change="onPlayersCheckChange" v-model="players_check">
        <van-checkbox
          v-for="player in playersByTeam"
          :name="player.account_id"
          :key="player.account_id"
          :checked-color="playersColors[player.account_id]"
        >{{player.name}}[Team {{player.team_id}}]</van-checkbox>
      </van-checkbox-group>
    </div>
  </div>
</template>

<script>
import "ol/ol.css";
import * as ol from "ol";
import TileLayer from "ol/layer/Tile";
import ImageStaticSource from "ol/source/ImageStatic";
import ImageLayer from "ol/layer/Image";
import OSM_Source from "ol/source/OSM";
import TileDebugSource from "ol/source/TileDebug";
import { getCenter } from "ol/extent";
import * as style from "ol/style";
import * as geom from "ol/geom";
import * as source from "ol/source";
import Projection from "ol/proj/Projection";
import axios from "axios";
import rc from "randomcolor";
import VectorLayer from "ol/layer/Vector"; //ImageStatic本身不能用来放置图标,必须弄个VectorLayer
const MAP_IMAGES = {
  Vikendi:
    "http://n1-q.mafengwo.net/s16/M00/1F/16/CoUBUl6J6-WAfTq9ABN1dkMMLI4971.jpg#DihorOtok_Main",
  "Erangel (Remastered)":
    "http://n1-q.mafengwo.net/s16/M00/24/CD/CoUBUl6J8CGAZ8FWACwGssFmNzs911.jpg#Baltic_Main.jpg.jpg",
  Miramar:
    "http://b1-q.mafengwo.net/s16/M00/25/07/CoUBUl6J8DuABPwhAB3VGbsEWx0692.jpg#Desert_Main.jpg.jpg",
  Erangel:
    "http://n1-q.mafengwo.net/s16/M00/25/14/CoUBUl6J8E-AbIDmABcvo6NWiPE512.jpg#Erangel_Main.jpg.jpg",
  Sanhok:
    "http://p1-q.mafengwo.net/s16/M00/25/2E/CoUBUl6J8HWAB3mbABe2H5mDyy8107.jpg#Savage_Main.jpg.jpg"
};
const MAP_LENGTH_CENTIMETERS = {
  Vikendi: 612000,
  "Erangel (Remastered)": 816000,
  Miramar: 816000,
  Erangel: 816000,
  Sanhok: 408000
};

const MAP_NAME = "Miramar";
const Characters_5275ac61d5ec46d9a910ca37c1ef3938 =
  "http://m.tuniucdn.com/fb2/t1/G6/M00/A2/9B/Cii-U16cReeIZHe_ALD-IcFeeLoAAMXpQDDXBoAsP4570.json";
const MatchInfo_5275ac61d5ec46d9a910ca37c1ef3938 =
  "http://m.tuniucdn.com/fb2/t1/G6/M00/A2/9B/Cii-TF6cRjOIf-JjAAAnfLXPGOgAAMXpQGHwkAAACeU94.json";

let match_id =
  "match.bro.official.pc-2018-06.steam.squad.na.2020.02.02.12.71ebe6e9-7ce8-40f1-b541-6dcf06f13380";

match_id =
  "match.bro.official.pc-2018-06.steam.squad.na.2020.02.08.12.5275ac61-d5ec-46d9-a910-ca37c1ef3938";

var extent = [
  0,
  0,
  MAP_LENGTH_CENTIMETERS[MAP_NAME],
  MAP_LENGTH_CENTIMETERS[MAP_NAME]
];
console.log("extent", JSON.stringify(extent));
var projection = new Projection({
  extent: extent,
  code: "xkcd-image",
  units: "pixels"
});
export default {
  name: "HelloWorld233",
  data() {
    return {
      // msg: "Welcome to Your Vue.js App",
      map: null,
      vector_layer: new VectorLayer({ source: new source.Vector() }),
      character_datas: [],
      match_info: {},
      players_check: []
    };
  },
  computed: {
    characters_coords: function() {
      return this.character_datas.map(e => {
        let points = e.arrayOfCharacters.map(c => {
          return [
            c.character.location.x,
            c.character.location.y
            // MAP_LENGTH_CENTIMETERS[MAP_NAME] - c.character.location.y
          ];
        });
        points = points.map(e => [
          e[0],
          MAP_LENGTH_CENTIMETERS[MAP_NAME] - e[1]
        ]);
        return points;
      });
    },
    playersByTeam() {
      if (this.match_info && this.match_info["players"]) {
        return this.match_info.players.sort((a, b) => a.team_id - b.team_id);
      }
      return [];
    },
    playerLineStringFeatures() {
      let res = {};
      if (this.match_info && this.match_info["players"]) {
        // debugger;
        for (let d of this.character_datas) {
          let account_id = d["account_id"];
          if (account_id) {
            let points = d.arrayOfCharacters.map(c => {
              return [
                c.character.location.x,
                // c.character.location.y
                MAP_LENGTH_CENTIMETERS[MAP_NAME] - c.character.location.y
              ];
            });
            let lineString = new geom.LineString(points);
            let feature = new ol.Feature({
              geometry: lineString
            });
            let sty = new style.Style({
              stroke: new style.Stroke({ color: "red" })
            });
            feature.setStyle(sty);
            // return feature;
            res[account_id] = feature;
          }
        }
      }
      return res;
    },
    playerLabelFatures() {
      let res = {};
      if (this.playersByTeam.length) {
        for (let d of this.character_datas) {
          let account_id = d["account_id"];
          if (account_id) {
            let filtered = d.arrayOfCharacters.filter(
              e =>
                e.in_event == "LogPlayerKill" ||
                e.in_event == "LogPlayerTakeDamage" 
                // ||e.in_event == "LogPlayerAttack"
            );
            // console.log(filtered);
            let points = filtered.map(c => {
              let loc = [
                c.character.location.x,
                // c.character.location.y
                MAP_LENGTH_CENTIMETERS[MAP_NAME] - c.character.location.y
              ];
              let feat = new ol.Feature({
                geometry: new geom.Point(loc)
              });
              feat.setStyle(
                new style.Style({
                  // fill: new style.Fill({color:"rgba(0,0,0,0)"}),
                  image: new style.Icon({
                    src:
                      "http://n1-q.mafengwo.net/s16/M00/2B/DA/CoUBUl6J9SeAQwKuAAASj-NBxq0317.png"
                  }),
                  text: new style.Text({
                    font: "13px Microsoft YaHei",
                    text: c.in_event + ":" + c.info,

                    fill: new style.Fill({
                      color: this.playersColors[account_id]
                    })
                  })
                })
              );
              return feat;
            });
            res[account_id] = points;
          }
        }
      }

      return res;
    },
    playersColors() {
      let res = {};
      if (this.playersByTeam.length) {
        for (let player of this.playersByTeam) {
          let c = rc.randomColor({
            luminosity: "dark"
          });
          res[player.account_id] = c;
        }
      }
      return res;
    }
  },
  async mounted() {
    let map = new ol.Map({
      layers: [
        new ImageLayer({
          source: new ImageStaticSource({
            attributions:
              '© <a href="http://xkcd.com/license.html">PUBG VIS</a>',
            imageExtent: extent,
            projection: projection,
            url: MAP_IMAGES[MAP_NAME]
          }),
          opacity: 0.5
        }),
        new TileLayer({ source: new TileDebugSource(), opacity: 0.5 })
      ],
      view: new ol.View({
        center: getCenter(extent),
        zoom: 1,
        // maxZoom: 8,
        // minZoom: 1,
        extent: extent,
        resolution: MAP_LENGTH_CENTIMETERS[MAP_NAME] / 400,
        projection: projection
      }),
      target: "map"
    });
    this.map = map;
    let layer = this.vector_layer;
    let anchor = new ol.Feature({
      geometry: new geom.Point([612000, 612000])
    });
    anchor.setStyle(
      new style.Style({
        image: new style.Icon({
          src:
            "http://n1-q.mafengwo.net/s16/M00/2B/DA/CoUBUl6J9SeAQwKuAAASj-NBxq0317.png"
        })
      })
    );
    layer.getSource().addFeature(anchor);
    map.addLayer(layer);
    await this.getMatchInfo();
    await this.getCharactersData();
    let line_coords = this.character_datas.map(e => {
      let points = e.arrayOfCharacters.map(c => {
        return [
          c.character.location.x,
          c.character.location.y
          // MAP_LENGTH_CENTIMETERS[MAP_NAME] - c.character.location.y
        ];
      });
      // points = points.filter(e => {
      //   if (e[0] == 0 && e[1] == 0) {
      //     return false;
      //   }
      //   return true;
      // });
      // let lastPoint = points[points.length - 1];
      // console.log("last point", lastPoint[0], lastPoint[1]);
      // if (lastPoint[0] == 0 && lastPoint[1] == 0) {
      //   // debugger
      //   points.pop();
      // }
      points = points.map((e, i, a) => {
        if (e[0] == 0 && e[1] == 0) {
          console.log("???", e, i, a);
        }
        return [e[0], MAP_LENGTH_CENTIMETERS[MAP_NAME] - e[1]];
      });
      return points;
    });
    let lines = line_coords.map(points => {
      // debugger
      let poly = new ol.Feature({
        geometry: new geom.LineString(points)
      });
      let color = rc.randomColor();
      poly.setStyle(
        new style.Style({
          // fill:new style.Fill({color:"red"}),
          stroke: new style.Stroke({ color: color })
        })
      );
      return poly;
      // layer.getSource().addFeature(poly);
    });

    for (let line of lines) {
      // debugger
      layer.getSource().addFeature(line);
    }
    // debugger

    // debugger;
    // let test_charas = this.character_datas.filter(
    //   e => e.arrayOfCharacters.length > 500
    // )[13].arrayOfCharacters;
    // let locations = test_charas.map(e => e.character.location);
    // for (let loc of locations) {
    //   let point = new ol.Feature({
    //     geometry: new geom.Point([
    //       loc.x,
    //       MAP_LENGTH_CENTIMETERS[MAP_NAME] - loc.y
    //     ])
    //   });
    //   // point.setStyle(
    //   //   new style.Style({
    //   //     // image: new style.Icon({// src:"http://n1-q.mafengwo.net/s16/M00/2B/DA/CoUBUl6J9SeAQwKuAAASj-NBxq0317.png"})
    //   //   })
    //   // );
    //   await new Promise(resolve => {
    //     setTimeout(() => {
    //       layer.getSource().addFeature(point);
    //       resolve();
    //     }, 50);
    //   });
    // }

    // console.log(test_charas);
    // debugger;
    // debugger;
  },
  methods: {
    getCharactersData: function() {
      return new Promise(resolve => {
        axios
        .get(Characters_5275ac61d5ec46d9a910ca37c1ef3938)
          // .get(`http://localhost:3000/api/characters/${match_id}`)
          .then(axresp => {
            // debugger
            this.character_datas = axresp.data;
            resolve();
          })
          .catch(axerr => {
            debugger;
          });
      });
    },
    getMatchInfo: function() {
      return new Promise(resolve => {
        axios
        .get(MatchInfo_5275ac61d5ec46d9a910ca37c1ef3938)
          // .get(`http://localhost:3000/api/match/${match_id}`)
          .then(axresp => {
            this.match_info = axresp.data;
            resolve();
          })
          .catch(axerr => {
            debugger;
          });
      });
    },
    test() {
      /**@type {VectorLayer} */
      let layer = this.vector_layer;
      let source = layer.getSource();
      let allFeatures = source.getFeatures();
      // console.log(allFeatures);
      source.clear();
      // debugger
    },
    onPlayersCheckChange(names) {
      // debugger;
      this.vector_layer.getSource().clear();
      let account_ids = names;
      let lineStringfeatures = account_ids.map(account_id => {
        let feature = this.playerLineStringFeatures[account_id];
        feature.setStyle(
          new style.Style({
            stroke: new style.Stroke({
              color: this.playersColors[account_id]
            })
          })
        );
        return feature;
      });
      // let labels = (_ => {
      //   let raw = Object.values(this.playerLabelFatures);
      //   let arr = [];
      //   for (let f of raw) {
      //     for (let c of f) {
      //       arr.push(c);
      //     }
      //   }
      //   return arr;
      // })();

      let pointFeatures = account_ids.map(account_id => {
        let fs = this.playerLabelFatures[account_id];
        return fs;
      });
      for (let feats_ppp of pointFeatures) {
        // debugger;
        this.vector_layer.getSource().addFeatures(feats_ppp);
      }
      // debugger

      this.vector_layer.getSource().addFeatures(lineStringfeatures);
      // this.vector_layer.getSource().addFeatures(labels);
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
@mapSize: 800px;
.the-map-component {
  display: flex;
  #map {
    width: @mapSize;
    height: @mapSize;
  }
  .h-check-players {
  }
}
</style>
